package com.java.netty.client.nio.nettysimple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @Author: Dgg
 * @Date: 2021/12/12 21:43
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
	//当通道就绪时就会触发
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("Client信息:" + ctx);
		ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Server", CharsetUtil.UTF_8));
	}

	//当通道有读取时间时候触发
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("客户端监听到数据");
		ByteBuf byteBuf = (ByteBuf) msg;
		System.out.println("Received a message from the server" + byteBuf.toString(CharsetUtil.UTF_8));
		System.out.println("server-ip:" + ctx.channel().remoteAddress());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
